/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gandalf.servlet;

import gandalf.controller.CartJpaController;
import gandalf.controller.RezervacijaJpaController;
import gandalf.controller.StrankaJpaController;
import gandalf.controller.VstopnicaJpaController;
import gandalf.controller.exceptions.NonexistentEntityException;
import gandalf.model.Stranka;
import gandalf.model.Cart;
import gandalf.model.Nakup;
import gandalf.model.Postavka;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author tincek
 */
public class Placaj extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {


            if (request.getParameter("Submit").equals("Placaj")) {

                String nacinPlacila = request.getParameter("mf_cardtype");
                CartJpaController cartDao = new CartJpaController();
                StrankaJpaController strankaDao = new StrankaJpaController();
                RezervacijaJpaController rezervacijaDao = new RezervacijaJpaController();

                Long strankaId = getIdStrankeIzSeje(request);
                Stranka stranka = null;
                Long cartId = getIdKosariceIzSeje(request);
                Cart cart = null;
                if (cartId != null) {
                    cart = cartDao.findCart(cartId);
                }
                VstopnicaJpaController vstopnicaDao = new VstopnicaJpaController();

                if (strankaId != null) {
                    stranka = strankaDao.findStranka(strankaId);





                    Nakup nakup = new Nakup();
                    nakup.setCena(cart.getVsotaCene().doubleValue());
                    nakup.setDatumPlacila(new Date());
                    nakup.setNacinPlacila(nacinPlacila);
                    nakup.setStranka(stranka);
                    

                    String opis = "";
                    if (cart != null && !cart.getPostavka().isEmpty()) {
                        for (Postavka p : cart.getPostavka()) {
                            vstopnicaDao.odstejKolicino(p.getVstopnica().getId(), p.getKolicina());
                            opis += p.getVstopnica().getNaziv() + " "
                                    + p.getKolicina() + " x " + p.getVstopnica().getCena() + " EUR ";

                        }
                    }
                    opis += " Skupaj: " + cart.getVsotaCene();
                    nakup.setOpis(opis);

                    List<Nakup> nakupi = new ArrayList<Nakup>();
                    nakupi.add(nakup);
                    stranka.setNakupi(nakupi);
                    try {
                        strankaDao.uredi(stranka);
                    } catch (NonexistentEntityException ex) {
                        Logger.getLogger(Placaj.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        Logger.getLogger(Placaj.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        rezervacijaDao.destroyRezervacije(rezervacijaDao.findRezervacijaWithStranka(strankaId));
                    } catch (NonexistentEntityException ex) {
                        Logger.getLogger(Placaj.class.getName()).log(Level.SEVERE, null, ex);
                    }



                    /*
                    System.out.println("RAČUN: \n");
                    System.out.println(stranka.getIme() + " " + stranka.getPriimek() + "\n");

                    if (cart != null && !cart.getPostavka().isEmpty()) {
                        for (Postavka p : cart.getPostavka()) {
                            System.out.println(p.getVstopnica().getNaziv() + " "
                                    + p.getKolicina() + " x " + p.getVstopnica().getCena() + " EUR  ");
                            System.out.println("SKUPAJ: " + cart.getVsotaCene());
                            System.out.println("\nNACIN PLACILA: " + nacinPlacila);
                        }
                    }*/
                    if (cartId != null) {
                        try {
                            cartDao.destroy(cartId);
                        } catch (NonexistentEntityException ex) {
                            Logger.getLogger(Placaj.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    request.getSession().invalidate();
                    response.sendRedirect("index.jsp");

                } else {
                    if (cart != null && !cart.getPostavka().isEmpty()) {
                        for (Postavka p : cart.getPostavka()) {
                            vstopnicaDao.odstejKolicino(p.getVstopnica().getId(), p.getKolicina());

                        }
                    }
                    request.getSession().invalidate();
                    response.sendRedirect("index.jsp");
                }
            }
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Placaj</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Placaj at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             *
             */

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private Long getIdStrankeIzSeje(HttpServletRequest request) {
        Long id = null;
        Object o = request.getSession().getAttribute("stranka_id");
        if (o != null && o instanceof Long) {
            id = (Long) o;
        }

        return id;
    }

    private Long getIdKosariceIzSeje(HttpServletRequest request) {
        Long id = null;
        Object o = request.getSession().getAttribute("kosarica_id");
        if (o != null && o instanceof Long) {
            id = (Long) o;
        }

        return id;
    }

    private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
}
